<?php
namespace app\model;



class Pay {

    static function after($params,$system){
        global $_G, $_P;
        if(($params['result'] == 'success' && $params['from'] == 'notify') || ($params['from'] == 'return' &&  $params['type'] == 'delivery' )){
            $order = Order::getByTId($params['tid']);
            if($order['paystate'] == 0 && !empty($order['id'])){
                $data = self::readyPayParams($params); 
                //再次与微信支付较对
                $checkresult = checkWechatPayByOrderNo($params['tid'],$system);
                if($checkresult['errcode'] == 0 && $params['card_fee']==$checkresult['fee']){
                    $config =   Theme::getConfig($order['themeid']);
                    $chajia = sprintf("%.2f",floatval($config['groupprice']-$config['primeprice']));

                    if (($order['orderfee']>0 && $data['realfee'] == $order['orderfee'] && ($order['orderfee'] == $config['joinfee'] ||  $order['orderfee'] == $chajia || $order['orderfee'] == $config['primeprice'] || $order['orderfee'] == $config['groupprice'] || $order['orderfee'] == $config['groupprice2'] || $order['orderfee'] == $config['joinfee'] || $order['orderfee'] == $config['joinfee2'] || $order['orderfee'] == $config['joinfee3']) ) || ($config['yukuan']>0 && TIMESTAMP>$config['yukuantime'])){ 
                        $record = Record::getById($order['masterid']);
                        $relationtable = Relation::getByThemeId($order['themeid'],$record['openid']);
                        $data['workerid']=$relationtable['workerid'];

                        $Recordstate = Record::update($order['masterid'],array('status'=>1));
                        if ($Recordstate) {
                            $Orderstate = Order::update($order['id'],$data);
                            if ($Orderstate) {
                                self::commonBiz($system,$order['masterid'],$order['themeid'],$data['realfee']);
                            }
                        }
                    }
                }
            }
        }
    }

    static function readyPayParams($params){
        global $_G, $_P;
        $data = array(
            'paystate'=> 1,
            'paytime' => TIMESTAMP,
            'status'  => 1,
            'type'    => empty($params['type']) ? 'wechat':$params['type'],
            'realfee' => $params['card_fee'],
            'uniontid'=> $params['uniontid'],
            'usecard' => $params['is_usecard'],
            'usecardid'=> $params['card_id'],
            'transaction_id'=>$params['tag']['transaction_id'],
        );
        return $data;
    }

    static function commonBiz($system,$recordid,$themeid,$realfee){
        global $_G, $_P;
        $theme = Theme::getThemeById($themeid);
        $config = 	Theme::getConfig($themeid);
        $record = Record::getById($recordid);
        $url = Util::themeUrlnew('index',$themeid,$theme['softkey']);
        
        // db_query("UPDATE ".tablename(t_worker)." SET paycount = paycount +1 WHERE uniacid = ".$record['uniacid']." and themeid = ".$record['themeid']." and uid =".$record['workerid']);

        Theme::workerreport($themeid,$record['workerid'],array('record' =>1));
        if ($record['workerid'] == $record['fromuid']) {
            Theme::workerreport($themeid,$record['workerid'],array('recordzx' =>1));
        }
        Theme::workerreport($themeid,$record['workerid'],array('fee' =>$record['fee']));
        
        if (!empty($record['fromuid'])) {
            db_query("UPDATE ".tablename(t_fans)." SET tuijian = tuijian + 1 WHERE themeid = '{$themeid}' and uid ={$record['fromuid']}");
        }
        //$p = array(":uniacid"=>$_G['mpid'],":themeid"=>$themeid);
        //db_query("UPDATE ".tablename(t_theme)." SET recordcount = recordcount + 1,ordercount = ordercount + " . $record['fee'] . " WHERE uniacid = :uniacid and id =:themeid",$p);


        if ($system['ruanjian']==0 && $system['softstyle']==5 ) {
            if(!empty($record['address']) && $record['type']==0){
                db_query("UPDATE ".tablename(t_shengshi)." SET recordid = " . $recordid . " WHERE areaId =".$record['address']);
            }
        }


        if ($system['tixing']==1 || ($system['tixing']==3 && !empty($system['neworder']))){
            // $record = Record::getById($order['masterid']);
            // echo $order['masterid'];
            $worker = Worker::getThemeWorkerByUid($record['workerid'],$themeid,1);
            // var_dump($worker);
            if ($record['type']==9){
                $orderType='单买';
            }elseif ($record['type']==1){
                $orderType='团员';
            }elseif (intval($config['maxcountall'])>1) {
                $orderType='团长';
            }else{
                $orderType='已支付';
            }

            $paycounttoday = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE status > 0 and workerid = '{$record['workerid']}' and addtime>'{$todaytime}' and themeid = '{$themeid}' " );
            $paycount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE status > 0 and workerid = '{$record['workerid']}' and themeid = '{$themeid}' " );
            $message = array(
                'server'  => DOMAIN0,
                'softname'  => MODULE_NAME,
                'uniacid'   => $_G['mpid'],
                'themeid'   => $themeid,
                'qruserid'   => $worker['qruserid'],
                "url"       => Util::themeUrlnew('w_order',$themeid,$theme['softkey']),        
                "openid"    =>$worker['openid'],
                "first"     =>'截止' .date('d日H:i分') .', 您今日成交【 ' . $paycounttoday .' 】单, 总计 ' . $paycount .' 单',
                "tradeDateTime"  => date('Y-m-d H:i:s'),
                "orderType"  => $orderType,
                "customerInfo"  => $record['username'] ,
                "orderItemName"  => '客户电话',
                "orderItemData"  => $record['mobile'],
                "remark"    => '微信昵称：'.$record['nickname'],
            );
            // var_dump($message);
            if ($system['tixing']==1) {
                if (!empty($worker['qruserid'])) {
                    $rec = Poster::ServerQR($system,'send',$message);
                }
            }else{
                // $rec = Util::sendNeworder($message,$system);
            }
            // var_dump($rec);
            // exit;
        }
            
        if($record['type'] == 0){
            db_update( t_record, array("tuannum"=>1), array ('pid' => $record['pid']) );
        }
        if($record['type'] == 1){
            $precord = Record::getById($record['pid']);
            $url .= "&recordid=".$record['pid'];
            $count = Record::getAttendDetailNumByPId($record['pid']);
            $tips = '';
            if($config['iscode']==1){
                $code = Code::getCanUseByThemeId($themeid);
                if(!empty($code)){
                    Code::setUse($code,$record);
                }
            }
            if ($record['renshu']==1) {
                $neednum = intval($config['maxcountall2'])-1;
            }else{
                $neednum = intval($config['maxcountall'])-1;
            }

            db_update( t_record, array("tuannum"=>$count+1), array ('pid' => $record['pid']) );
            if($count >= $neednum){
                //Record::update($record['pid'],array('isfinish'=>1));
                $record['isfinish']=1;
                Record::setIsfinish($record['pid']);
                // $code = Code::getCanUseByThemeId($themeid);
                // if(!empty($code)){
                //     Code::setUse($code,$precord);
                // }
                // $tips = "，拼团成功啦！";
                // $detaillist = Record::getDetailListByPid($record['pid']);
                // $message = array(
                //     "url"       =>$url,
                //     "keyword1"  =>$theme['title'],
                //     "keyword2"  =>$precord['username'],
                //     "keyword3"  =>$neednum,
                //     "remark"    =>!empty($system['success_remark']) ?$system['success_remark']:'感谢您的参与，点击查看活动详情,客服电话:'.$theme['mobile'],
                // );
                // foreach ($detaillist as $index=>$row){
                //     $message['openid'] = $row['openid'];
                //     $message['first'] = $row['nickname'].'您好，您参加的团'.$tips;
                //     Util::sendPinTuanSuccessNotice($message,$system);
                // }
            }
            // $progress = '需要'.$neednum.'人拼团成功，目前已有'.$count.'人参团'.$tips;
            // $message = array(
            //     "url"       =>$url,
            //     "openid"    =>$precord['openid'],
            //     "first"     =>$precord['nickname'].'团长您好，有新团员【'.$record['nickname'].'】参团'.$tips,
            //     "keyword1"  =>$theme['title'],
            //     "keyword2"  =>$progress,
            //     "remark"    =>!empty($system['progress_remark']) ?$system['progress_remark']:'感谢您的参与，点击查看活动详情,客服电话:'.$theme['mobile'],
            // );
            // Util::sendProgressNotice($message,$system);
        }else{
            if($record['type'] == 0 && $record['pid'] == 0){
                $data = array();
                $data['pid']=$record['id'];
                Record::update($record['id'],$data);
            }
            $url .= "&recordid=".$recordid;
        }

        if ($system['qrlist']==1 ) {
            if ($config['qrlistmode']==0 || ($config['qrlistmode']==1 && $record['isfinish']==1)) {
                $sql = "SELECT * FROM " . tablename ( t_qrlist ) . " 
                    WHERE themeid = '{$themeid}' and state = 1 and usercount<qrnum ORDER BY displayorder asc, id asc ";
                $list = db_find ( $sql);
                if (!empty($list)) {
                    $qrliststate = db_query("UPDATE ".tablename(t_qrlist)." SET usercount = usercount+1 WHERE id =".$list['id']);
                    $recordstate = db_query("UPDATE ".tablename(t_record)." SET qrimgid = '". $list['id'] ."',qrimg ='" .$list['qrimg']."' WHERE id = ".$recordid );
                }
            }
        }

        if ($config['yukuan']>0 && TIMESTAMP>$config['yukuantime'] && $config['yukuanfenxiao']==1){
            exit;
        }


        //自己下单有红包
        if($config['hborderfee1']>0 && $system['autored']==2){
            $ishbopen = Comm::addhborder($system,$themeid,$config,$record['uid'],$record['openid']);
        }
            
        $comm1 = max(floatval($config['comm12']),floatval($config['comm2']));
        $comm1 = $comm1+floatval($config['comm22'])+floatval($config['comm32'])+floatval($config['comm62']);


        if ($system['jiage']==0 && $comm1>=$realfee){
            exit;
        }
        //更新关系表,上下级锁定以及员工锁定
        $relationtable = Relation::getByThemeId($themeid,$record['openid']);
        if(!empty($relationtable)){
            $data = array();
            if( $config['isfreeze']==1){
                $data["isfrozen"]=1;
            }
            $data["isorder"]=1;
            Relation::update($relationtable['id'],$data);
        }
 
        //抽奖报名后增加抽奖机会
        if ($system['fanpai']==1 && $config['fanpaigroupid']>0) {
            if ($config['fanpaibaoming'] > 0){
                $sql = "SELECT * FROM " . tablename ( t_fanpaijihui ) . " WHERE themeid= " . $themeid . " and  uid= " . $record['uid'] . " and type = 1";
                $jihuilist = db_select ( $sql );
                if (empty($jihuilist)){
                    $tempdata = array(
                        'themeid'   => $themeid,
                        'uniacid'   => $_G['mpid'],
                        'uid'       => $record['uid'],
                        'openid'    => $record['openid'],
                        'nickname'  => $record['nickname'],
                        'avatar'    => $record['avatar'],
                        'status'    => 0,
                        'type'    => 1,
                        'jihui'    => $config['fanpaibaoming'],
                        'addtime'   => TIMESTAMP,
                        'workerid' => $record['workerid'],
                    );
                    if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
                        $data['workerid_old']  = $workerid;
                    }
                    $insertid = db_insert(t_fanpaijihui, $tempdata);
                    db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + " . $config['fanpaibaoming'] . " WHERE themeid = " . $themeid . " and uid = ".$record['uid'] ."");
                }
            }
            if ($config['fanpaiyaoqing'] > 0){
                if (!empty($record['fopenid']) && $record['fopenid'] != $record['openid']){

                    $pm = array(":themeid"=>$themeid,":openid"=>$record['fopenid']);
                    $member = db_find("SELECT * FROM ".tablename(t_fans)."
                            WHERE themeid = :themeid and openid = :openid",$pm);
                    
                    $tempdata = array(
                        'themeid'   => $themeid,
                        'uniacid'   => $_G['mpid'],
                        'uid'       => $record['fromuid'],
                        'openid'    => $record['fopenid'],
                        'nickname'  => $member['nickname'],
                        'avatar'    => $member['avatar'],
                        'fromuid'   => $record['uid'],
                        'fopenid'   => $record['openid'],
                        'status'    => 0,
                        'type'      => 2,
                        'jihui'     => $config['fanpaiyaoqing'],
                        'addtime'   => TIMESTAMP,
                        'workerid'  => $record['workerid'],
                    );
                    if (!empty($record['uid_old'])) {
                        $tempdata['fromuid_old']=$record['uid_old'];
                        $tempdata['fopenid_old']=$record['openid_old'];
                        $tempdata['workerid_old']=$record['workerid_old'];
                    }
                    $insertid = db_insert(t_fanpaijihui, $tempdata);
                    db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + " . $config['fanpaiyaoqing'] . " WHERE themeid = " . $themeid . " and uid = ".$record['fromuid'] ."");
                }
            }
        }

        //员工提成
        if($config['iscomm'] == 1 && $system['fenxiao06'] == 1 && !empty($config['comm61']) && !empty($record['workerid'])){

            if ($system['jiage']==0 || ($system['jiage']>0 && $record['jiagetype']==$config['joinname'] )){
                $randomfee = floatval(mt_rand($config['comm61']*100,$config['comm62']*100)/100);
            }elseif ($system['jiage']>0 && $record['jiagetype']==$config['joinname2']) {
                $randomfee = floatval(mt_rand($config['comm61_jiage2']*100,$config['comm62_jiage2']*100)/100);
            }elseif ($system['jiage']>1 && $record['jiagetype']==$config['joinname3']) {
                $randomfee = floatval(mt_rand($config['comm61_jiage3']*100,$config['comm62_jiage3']*100)/100);
            }

            if($randomfee >= 0.3){
                $recommed2 = Comm::WorkerRecommendCommAfterPayYxiaun($config,$record,$randomfee);
            }
        }

        $isworker = Worker::getThemeWorkerByOpenidzhuce($record['fopenid'],$themeid,1);
        //员工没有红包
        if ($config['commworker']==1 && !empty($isworker) ){
            $workerhb=1;
        }else{
            $workerhb=0;
        }

        if($config['iscomm'] == 1 && $workerhb==0 && $system['fenxiao01'] > 0 && !empty($record['fopenid']) && ($record['fopenid'] != $record['openid'] || !empty($isworker)) && !empty($config['comm11']) && !empty($config['comm1'])){
            if ($system['jiage']==0 || ($system['jiage']>0 && $record['jiagetype']==$config['joinname'] )){
                //新版概率随机
                $first = intval($config['comm13']);
                $second= $first + intval($config['comm13_2']);
                $gailv = mt_rand(0,99);
                if ($first==0 || $first==100 || $gailv < $first ) {
                    $randomfee = floatval(mt_rand($config['comm11']*100,$config['comm12']*100)/100);
                }elseif ($gailv < $second && $config['comm12_2']!=0 ) {
                    $randomfee = floatval(mt_rand($config['comm11_2']*100,$config['comm12_2']*100)/100);
                }elseif ($config['comm12_3']!=0 ) {
                    $randomfee = floatval(mt_rand($config['comm11_3']*100,$config['comm12_3']*100)/100);
                }else{
                    $randomfee = floatval(mt_rand($config['comm11']*100,$config['comm12']*100)/100);
                }
            }elseif ($system['jiage']>0 && $record['jiagetype']==$config['joinname2']) {
                $randomfee = floatval(mt_rand($config['comm11_jiage2']*100,$config['comm12_jiage2']*100)/100);
            }elseif ($system['jiage']>1 && $record['jiagetype']==$config['joinname3']) {
                $randomfee = floatval(mt_rand($config['comm11_jiage3']*100,$config['comm12_jiage3']*100)/100);
            }

            if($randomfee >= 0.3){
                $recommed = Comm::dealRecommendCommAfterPay($config,$record,$randomfee);
            }


//            if($recommed > 0){
//                $fmember = Fans::getByTheme($record['themeid'],$record['fopenid']);
//                Comm::recommedCommNotice($url.'&randomfee='.$randomfee,$record,$system,$fmember['nickname'],$theme);
//            }
            //员工没有红包
            if (!empty($recommed)) {

            $relation2 = Relation::getByThemeId($themeid,$record['fopenid']);
            $workerhb = Worker::getThemeWorkerByOpenid($relation2['popenid'],$themeid,1);
            if (!empty($workerhb) && $config['commworker']==1){
                $workerhb=1; 
            }else{
                $workerhb=0;
            }
            $isworker = Worker::getThemeWorkerByOpenid($record['fopenid'],$themeid,1);
            if($workerhb==0 && empty($isworker) && !empty($config['comm21'] && $system['fenxiao01'] > 1)){
                if ($system['jiage']==0 || ($system['jiage']>0 && $record['jiagetype']==$config['joinname'] )){
                    // $randomfee2 = floatval(mt_rand($config['comm21']*100,$config['comm22']*100)/100);
                    //新版概率随机
                    $first = intval($config['comm23']);
                    $gailv = mt_rand(0,99);
                    if ($first==0 || $first==100 || $gailv < $first ) {
                        $randomfee2 = floatval(mt_rand($config['comm21']*100,$config['comm22']*100)/100);
                    }elseif ($config['comm22_2']!=0 ) {
                        $randomfee2 = floatval(mt_rand($config['comm21_2']*100,$config['comm22_2']*100)/100);
                    }else{ 
                        $randomfee2 = floatval(mt_rand($config['comm21']*100,$config['comm22']*100)/100);
                    }

                }elseif ($system['jiage']>0 && $record['jiagetype']==$config['joinname2']) {
                    $randomfee2 = floatval(mt_rand($config['comm21_jiage2']*100,$config['comm22_jiage2']*100)/100);
                }elseif ($system['jiage']>1 && $record['jiagetype']==$config['joinname3']) {
                    $randomfee2 = floatval(mt_rand($config['comm21_jiage3']*100,$config['comm22_jiage3']*100)/100);
                }
                if($randomfee2 >=0.3){
                    if(!empty($relation2['popenid']) && $relation2['popenid'] != $record['openid'] && $relation2['popenid'] != $record['fopenid']){

                        //执行锁定级别
                        if( $config['isfreeze']==1){
                            $relationtable = Relation::getByThemeId($themeid,$record['fopenid']);
                            if(!empty($relationtable)){
                                $data = array("isfrozen"=>1);
                                Relation::update($relationtable['id'],$data);
                            }
                        }
                        $recommed2 = Comm::dealLevel2RecommendCommAfterPayYixuan($config,$record,$randomfee2,$relation2);
                        if (!empty($recommed2)) {
                        //员工没有红包                                
                        $relation3 = Relation::getByThemeId($themeid,$relation2['popenid']);
                        $workerhb = Worker::getThemeWorkerByOpenid($relation3['popenid'],$themeid,1);
                        if (!empty($workerhb) && $config['commworker']==1){
                            $workerhb=1;
                        }else{
                            $workerhb=0;
                        }
                        $isworker = Worker::getThemeWorkerByOpenid($relation2['popenid'],$themeid,1);
                        if($workerhb==0 && empty($isworker) &&  $recommed2>0 && $system['fenxiao01'] == 3 && !empty($config['comm31']) && !empty($relation2['popenid'])){
                            if ($system['jiage']==0 || ($system['jiage']>0 && $record['jiagetype']==$config['joinname'] )){
                                // $randomfee3 = floatval(mt_rand($config['comm31']*100,$config['comm32']*100)/100);
                                //新版概率随机
                                $first = intval($config['comm33']);
                                $gailv = mt_rand(0,99);
                                if ($first==0 || $first==100 || $gailv < $first ) {
                                    $randomfee3 = floatval(mt_rand($config['comm31']*100,$config['comm32']*100)/100);
                                }elseif ($config['comm32_2']!=0 ) {
                                    $randomfee3 = floatval(mt_rand($config['comm31_2']*100,$config['comm32_2']*100)/100);
                                }else{ 
                                    $randomfee3 = floatval(mt_rand($config['comm31']*100,$config['comm32']*100)/100);
                                }

                            }elseif ($system['jiage']>0 && $record['jiagetype']==$config['joinname2']) {
                                $randomfee3 = floatval(mt_rand($config['comm31_jiage2']*100,$config['comm32_jiage2']*100)/100);
                            }elseif ($system['jiage']>1 && $record['jiagetype']==$config['joinname3']) {
                                $randomfee3 = floatval(mt_rand($config['comm31_jiage3']*100,$config['comm32_jiage3']*100)/100);
                            }

                            if($randomfee3 >=0.3){
                                //确定上一级不为空并且不是本人和1,2级
                                if(!empty($relation3['popenid']) && $relation3['popenid'] != $record['openid'] && $relation3['popenid'] != $relation2['popenid'] && $relation3['popenid'] != $record['fopenid']){
                                    //执行锁定级别
                                    if( $config['isfreeze']==1){
                                        $relationtable = Relation::getByThemeId($themeid,$relation2['popenid']);
                                        if(!empty($relationtable)){
                                            $data = array("isfrozen"=>1);
                                            Relation::update($relationtable['id'],$data);
                                        }
                                    }
                                    $recommed3 = Comm::dealLevel3RecommendCommAfterPayYxiaun($config,$record,$randomfee3,$relation3);
                                }
                            }
                        }
                        }//comm31

//                        if($recommed2 > 0){
//                            $fmember2 = Fans::getByTheme($record['themeid'],$record['fopenid']);
//                            $record['fopenid'] = $relation2['popenid'];
//                            self::recommedCommNotice($url.'&randomfee='.$randomfee2,$record,$system,$fmember2['nickname'],$theme,2);
//                        }
                    }
                }
            }

            }



        }
        $message = array(
            "url"       =>$url,
            "openid"    =>$record['openid'],
            "first"     =>$record['username'].'您好，您已成功报名',
            "keyword1"  =>$theme['title'],
            "keyword2"  =>$theme['jubf'],
            "keyword3"  =>date('Y-m-d',$theme['begintime']).'~'.date('Y-m-d',$theme['endtime']),
            "remark"    =>!empty($system['attendok_remark']) ?$system['attendok_remark']:'感谢您的参与，点击查看活动详情,客服电话:'.$theme['mobile'],
        );
        Util::sendAttendNotice($message,$system);
    }

    static function getThemeWorkerByOpenid($openid,$themeid,$status = 1){
        global $_G, $_P;
        if(empty($openid)){
            $openid = $_G['openid'];
        }
        $params = array();
        $params[':openid'] = $openid;
        $params[':themeid'] = $themeid;
        $params[':status'] = $status;
        $row = db_find("SELECT * FROM ".tablename(t_worker)." WHERE 
                        themeid = :themeid and openid = :openid and status=:status",$params);
        return $row;
    }

    //微信支付通知order不存在记录检测2分钟内符合条件的记录
    static function checkNoPayOrderByParams($params)
    {
        if ($params['result'] == 'success' && $params['from'] == 'notify') {
            $pre_time = time() - 120;
            //检查2分钟内openid以及支付金额相同的未支付状态订单
            $check_limit_order = Db::name(t_order)->where(['openid' => $params['openid'], 'orderfee' => $params['fee'], 'paystate' => 0])->where('addtime', '>=', $pre_time)->find();
            if ($check_limit_order) {
                //日志记录修改前order信息
                yxlog(['pay_after_info' => $params, 'diff_order_info' => $check_limit_order], '支付差异订单');
                //开始修改order表的 ordersn\tid\uniontid  以支付通知对应的paylog表数据为准
                $update_data = [
                    'ordersn' => substr($params['tid'], 1),
                    'tid' => $params['tid'],
                    'uniontid' => $params['uniontid']
                ];
                Db::name(t_order)->where(['id' => $check_limit_order['id']])->update($update_data);
            }
        }
    }



}
